import { FC, useEffect, useState } from 'react'
import { usePage } from '@hs-admin/utils'
import { HsAdminProTable } from '@hs-admin/base-components'
import { ZoomOutOutlined } from '@ant-design/icons'
import { DatabaseList, Databasetitle } from '@/api/Database'

const TablePage: FC = () => {
  const [data, setData] = useState([])
  const [columns, setColumns] = useState<any[]>([])
  const [columnsStateMap, setColumnsStateMap] = useState({})
  const baseConfig = {
    title: '操作',
    dataIndex: 'action',
    render: (_name: any) => (
      <div className="flex items-center">
        <div>
          <ZoomOutOutlined className="mx-10px" />
        </div>
      </div>
    ),
    width: 50
  }
  const release_item_id = '349d78e8-9078-4316-9dd2-e272f88c41a1'

  const filters = (List: any) => {
    const arr: any = []
    List.map((item: any) => {
      const obj: any = {}
      if (item.available) {
        obj.title = item.comment
        obj.dataIndex = item.name
        obj.queryable = item.queryable
        obj.width = 225
      } else {
        return
      }
      arr.push(obj)
    })
    return arr
  }
  //获取数据表头
  const Databasetitles = () => {
    Databasetitle(release_item_id).then((res: any) => {
      setColumns([baseConfig, ...filters(res)])
      if (!Object.keys(columnsStateMap).length) {
        const obj: any = {
          action: {
            show: true,
            fixed: 'left'
          }
        }
        res.map((item: any) => {
          if (item.available !== 0) {
            obj[item.name] = {
              show: item.queryable ? true : false
            }
          } else {
            return
          }
        })
        setColumnsStateMap(obj)
      }
    })
  }
  const doRequest = () => {
    return DatabaseList({
      page: pagination.current,
      page_size: pagination.pageSize,
      id: release_item_id
    }).then((res) => {
      setData(res.items)
      return res
    })
  }
  const { pagination } = usePage(doRequest)
  useEffect(() => {
    Databasetitles()
  }, [])

  return (
    <>
      <HsAdminProTable
        columns={columns}
        rowKey="id"
        dataSource={data}
        pagination={false}
        scroll={{ x: 1500 }}
        columnsState={{ value: columnsStateMap, onChange: setColumnsStateMap }}
        options={{
          setting: {
            checkedReset: false
          }
        }}
      />
    </>
  )
}

export default TablePage
